package com.zhan.ielts.web.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhan.frame.core.dao.BaseService;
import com.zhan.frame.core.web.controller.BaseControllerImpl;
import com.zhan.frame.core.web.domain.CustomResult;
import com.zhan.frame.core.web.domain.Result;
import com.zhan.frame.core.web.domain.Result.Status;
import com.zhan.ielts.domain.Merchandise;
import com.zhan.ielts.domain.TradeInfo;
import com.zhan.ielts.domain.Users;
import com.zhan.ielts.domain.query.TradeInfoQuery;
import com.zhan.ielts.domain.vo.TradeInfoVo;
import com.zhan.ielts.domain.vo.TradeNotifyVo;
import com.zhan.ielts.service.MerchandiseService;
import com.zhan.ielts.service.TradeInfoService;
import com.zhan.ielts.service.TradeNotifyService;
import com.zhan.ielts.service.UsersService;

@Controller
@RequestMapping("/trade/info")
public class TradeInfoController extends BaseControllerImpl<TradeInfo, TradeInfoQuery> {

	private Logger log = LoggerFactory.getLogger(TradeInfoController.class);

	@Autowired
	private TradeInfoService tradeInfoService;

	@Autowired
	private MerchandiseService merchandiseService;

	@Autowired
	private UsersService usersService;

	@Autowired
	private TradeNotifyService tradeNotifyService;

	@Override
	protected BaseService<TradeInfo> getBaseService() {
		return tradeInfoService;
	}

	@SuppressWarnings({ "rawtypes" })
	@ResponseBody
	@RequestMapping(value = "/order", method = RequestMethod.POST)
	public CustomResult order(String userId, String subject, String duration) {
		log.debug("获取商品信息开始");

		Map map = new HashMap();
		// 检查userId 是否为空
		if (StringUtils.isEmpty(userId)) {
			return new CustomResult(0, "userId为空！", map);
		} else if (StringUtils.isEmpty(subject)) {
			return new CustomResult(0, "subject为空！", map);
		} else if (StringUtils.isEmpty(duration)) {
			return new CustomResult(0, "duration为空！", map);
		}

		// 检查userId 是否有效
		Users query = new Users();
		query.setId(userId);
		if (usersService.queryCount(query) < 1) {
			// return new Result(Status.ERROR, "userId无效！");
		}

		// 获取商品信息
		Merchandise merchandiseQuery = new Merchandise();
		merchandiseQuery.setSubject(subject);
		merchandiseQuery.setDuration(duration);

		System.out.println(subject + "--" + duration);
		System.out.println(merchandiseQuery);

		Merchandise merchandise = merchandiseService.queryOne(merchandiseQuery);
		if (merchandise == null) {
			return new CustomResult(0, "没有对应点商品信息！", map);
		}

		String orderInfo = "";
		try {

			orderInfo = tradeInfoService.generateOrderInfo(userId, merchandise);

			log.debug("获取商品信息结束");
		} catch (Exception e) {
			e.printStackTrace();
			return new CustomResult(0, "网络或系统错误！", map);
		}

		return new CustomResult(1, "", orderInfo);

	}

	@SuppressWarnings("rawtypes")
	@ResponseBody
	@RequestMapping(value = "/notify", method = RequestMethod.POST)
	public String notify(TradeNotifyVo entity, HttpServletRequest request) {
		log.debug("nofity商品信息开始");
		String result = "";

		try {
			Map<String, String> params = new HashMap<String, String>();
			Map requestParams = request.getParameterMap();
			for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
				}
				// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
				// valueStr = new String(valueStr.getBytes("ISO-8859-1"),
				// "gbk");

				log.debug("name=" + name + "  value=" + valueStr);
				params.put(name, valueStr);
			}

			result = tradeNotifyService.handleTradeNotify(entity, params);

			log.debug("nofity商品信息结束");
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}

		return result;

	}

	@ResponseBody
	@RequestMapping(value = "/verify", method = RequestMethod.POST)
	public CustomResult verify(String userId, String outTradeNo) {
		log.debug("验证商品信息开始");
		Map map = new HashMap();
		// 检查userId 是否为空
		if (StringUtils.isEmpty(userId)) {
			return new CustomResult(0, "userId为空！", map);
		}

		// 检查userId 是否有效
		Users query = new Users();
		query.setId(userId);
		if (usersService.queryCount(query) < 1) {
			return new CustomResult(0, "userId无效！", map);
		}
		String status = "";
		try {
			TradeInfoVo tradeInfoVo = new TradeInfoVo();
			tradeInfoVo.setUserId(userId);
			tradeInfoVo.setOutTradeNo(outTradeNo);
			status = tradeInfoService.verifyOrderInfo(tradeInfoVo);

			if (status.equals("1")) {
				log.debug("验证商品信息结束");
				return new CustomResult(1, "", map);
			} else {
				log.debug("验证商品信息结束");
				return new CustomResult(0, "", status);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new CustomResult(0, "系统错误！", map);
		}

	}

	/**
	 * 
	 * @param userId
	 * @param type
	 * @param receiptData
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/iap", method = RequestMethod.POST)
	public CustomResult iapVerify(String userId, String type, String subject, String receiptData) {
		log.debug("iap验证商品信息开始");
		Map map = new HashMap();
		// 检查userId 是否为空
		if (StringUtils.isEmpty(userId)) {
			return new CustomResult(0, "userId为空！", map);
		} else if (StringUtils.isEmpty(type)) {
			return new CustomResult(0, "type为空！", map);
		} else if (StringUtils.isEmpty(subject)) {
			return new CustomResult(0, "subject为空！", map);
		}

		// 检查userId 是否有效
		Users query = new Users();
		query.setId(userId);
		if (usersService.queryCount(query) < 1) {
			return new CustomResult(0, "userId无效！", map);
		}

		try {
			JSONObject jsonObj = tradeInfoService.iapVerify(userId, type, subject, receiptData);
			if (jsonObj.getInt("status") == 0) {
				log.debug("iap验证商品信息结束");
				if (subject.equalsIgnoreCase("2")) {
					return new CustomResult(1, "", jsonObj.getJSONObject("compositionCorrection"));
				}
				return new CustomResult(1, "", usersService.queryOne(query));
			} else {
				log.debug("iap验证商品信息结束");
				return new CustomResult(0, "", jsonObj.getInt("status"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new CustomResult(0, "系统错误！", map);
		}

	}

}
